package com.cskaoyan.controller.wx_cart;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.MemoryBean;
import com.cskaoyan.bean.bo.wx_cart.CartAddBO;
import com.cskaoyan.bean.bo.wx_cart.CartCheckoutBO;
import com.cskaoyan.bean.bo.wx_cart.CartUpdateBO;
import com.cskaoyan.bean.vo.wx_cart.CartCheckoutVO;
import com.cskaoyan.bean.vo.wx_cart.CartIndexVO;
import com.cskaoyan.service.wx_cart.WxCartService;
import com.cskaoyan.util.common.Constant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * @program: market
 * @description: 前台（微信）购物车的handler方法分发
 * @author: zhong
 * @create: 2022-07-19 10:47
 **/
@RestController
@RequestMapping("wx/cart")
public class WxCartController {
    @Autowired
    WxCartService wxCartService;
    @Autowired
    MemoryBean memoryBean;

    /**
     * //从使用shiro Util从session获取userId,
     *     private Integer getUserId() {
     *         Subject subject = SecurityUtils.getSubject();
     *         Session session = subject.getSession();
     *         Integer userId = (Integer) session.getAttribute("id");
     *         if (userId == null) {
     *             return -1;
     *         }
     *         return userId;
     *     }
     * //获取token
     *     private String getToken() {
     *         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
     *                 .getRequest();
     *         String token = request.getHeader("X-CskaoyanMarket-Token");
     *         return token;
     *     }
     *
     */

    //使用token从memoryBean中获取userId,Constant.WX_TOKEN_HEADER = "X-CskaoyanMarket-Token";
    private Integer getUserId(@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = memoryBean.tokenAndUserId.get(token);
        if (userId == null) {
            return -1;
        }
        return userId;
    }


    /**
     * @param "userId":memoryBean中获取
     * @return 购物车列表和信息
     * @auther zhong
     * @description wx/cart/index 显示购物车信息
     */
    @GetMapping("index")
    public BaseRespVo index(@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        CartIndexVO cartIndexVO = wxCartService.listProductsOp(userId);
        if (userId == -1) {
            return BaseRespVo.ok(cartIndexVO, "登录信息失效", Constant.NOT_FOUND_CODE);
        }
        return BaseRespVo.ok(cartIndexVO);
    }

    /**
     * @param "userId":memoryBean中获取
     * @return 加入购物车的商品总数量
     * @auther zhong
     * @description wx/cart/goodscount 显示购物车商品件数
     */
    @GetMapping("goodscount")
    public BaseRespVo goodsCount(@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId == -1) {
            return BaseRespVo.ok(0);
        }
        int countProduct = wxCartService.countProductOp(userId);
        return BaseRespVo.ok(countProduct);
    }

    /**
     * @param checkoutBO:cartId,addressId,couponId,userCouponId,grouponRulesId //确认购买信息→请求头参数
     * @return 商品列表信息，收货地址信息，折扣信息
     * @auther zhong
     * @description wx/cart/checkout 下单前信息确认
     */
    @GetMapping("checkout")
    public BaseRespVo checkout(CartCheckoutBO checkoutBO,@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId==-1) {
            return BaseRespVo.invalidData("登录信息失效");
        }
        CartCheckoutVO checkoutInfo = wxCartService.listCheckoutInfoOp(checkoutBO, userId);
        return BaseRespVo.ok(checkoutInfo);
    }

    /**
     * @param cartAddBO:购物车添加信息
     * @return 购物车产品总数量number
     * @auther zhong
     * @description wx/cart/add 添加购物车
     */
    @PostMapping("add")
    public BaseRespVo add(@RequestBody CartAddBO cartAddBO,@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId == -1) {
            return BaseRespVo.invalidData("登录信息失效");
        }
        int code = wxCartService.addOp(cartAddBO, userId).code;

        if (code == Constant.FORBIDDEN_CODE) {
            return BaseRespVo.invalidData("数据冲突：库存不足");
        } else if (code == Constant.UNAUTHORIZED_CODE) {
            return BaseRespVo.invalidData("数据异常：新增失败");
        } else {
            int totalNumber = wxCartService.countProductOp(userId);
            return BaseRespVo.ok(totalNumber);
        }
    }

    /**
     * @param cartAddBO:立即购买信息
     * @return cartId
     * @auther zhong
     * @description wx/cart/fastadd 立即购买商品,先判断添加购物车
     */
    @PostMapping("fastadd")
    public BaseRespVo fastAdd(@RequestBody CartAddBO cartAddBO,@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId == -1) {
            return BaseRespVo.invalidData("登录信息失效");
        }
        WxCartService.CartResp cartResp = wxCartService.addOp(cartAddBO, userId);
        int code = cartResp.code;
        if (code == Constant.FORBIDDEN_CODE) {
            return BaseRespVo.invalidData("数据冲突：库存不足");
        } else if (code == Constant.UNAUTHORIZED_CODE) {
            return BaseRespVo.invalidData("数据异常：新增失败");
        } else {
            return BaseRespVo.ok(cartResp.cartId);
        }
    }

    /**
     * @param updateInfo:更新购物车
     * @return 成功或失败code
     * @auther zhong
     * @description wx/cart/update 更新购物车的商品
     */
    @PostMapping("update")
    public BaseRespVo update(@RequestBody CartUpdateBO updateInfo, @RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId == -1) {
            return BaseRespVo.invalidData("登录信息失效");
        }
        int code = wxCartService.updateProductNumOp(updateInfo);
        if (code == Constant.FORBIDDEN_CODE) {
            return BaseRespVo.invalidData("数据冲突：库存不足");
        } else if (code == Constant.NOT_FOUND_CODE) {
            return BaseRespVo.invalidParameter("数据异常：更新失败");
        }
        return BaseRespVo.ok();
    }

    /**
     * @param delInfo:productIds[]
     * @return 成功或失败code
     * @auther zhong
     * @description wx/cart/delete 删除购物车的商品
     */
    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Map delInfo, @RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        List<Integer> productIds = (List<Integer>) delInfo.get("productIds");
        Integer userId = getUserId(token);
        if (userId == -1) {
            return BaseRespVo.invalidData("登录信息失效");
        }
        int code = wxCartService.delCartOp(productIds, userId);
        if (code == Constant.NOT_FOUND_CODE) {
            return BaseRespVo.invalidData("购物车信息错误");
        }
        return BaseRespVo.ok();
    }

    /**
     * @param checkedInfo:勾选确认或取消下单的商品
     * @return 成功或失败code
     * @auther zhong
     * @description wx/cart/checked 选择或取消选择商品
     */
    @PostMapping("checked")
    public BaseRespVo checked(@RequestBody Map checkedInfo,@RequestHeader(Constant.WX_TOKEN_HEADER) String token) {
        Integer userId = getUserId(token);
        if (userId == null) {
            userId = -1;
        }
        int code = wxCartService.updateCheckedOp(checkedInfo, userId);
        if (code == Constant.NOT_FOUND_CODE) {
            return BaseRespVo.invalidParameter("产品不在购物车中");
        }
        CartIndexVO cartIndexVO = wxCartService.listProductsOp(userId);
        return BaseRespVo.ok(cartIndexVO);
    }


}
